package org.finesys.codegen.controller;

import cn.hutool.core.io.IoUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.finesys.codegen.service.GeneratorService;
import org.finesys.common.core.module.R;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/generator")
@Tag(name = "代码生成")
public class GeneratorController {

    private final GeneratorService generatorService;

    /**
     * ZIP 下载生成代码
     *
     * @param tableIds 数据表ID
     * @param response 流输出对象
     */
    @SneakyThrows
    @GetMapping("/download")
    public void download(String tableIds, HttpServletResponse response) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        //生成代码
        for (String tableId : tableIds.split(",")) {
            generatorService.download(Long.valueOf(tableId), zipOutputStream);
        }
        IoUtil.close(zipOutputStream);
        // 压缩数据
        byte[] data = outputStream.toByteArray();
        response.reset();
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment;filename=%s.zip", tableIds));
        response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
        response.setContentType(String.format("%s;%s", MediaType.APPLICATION_OCTET_STREAM_VALUE, "charset=UTF-8"));
        IoUtil.write(response.getOutputStream(), false, data);
    }

    /**
     * 目标目录生成代码
     */
    @SneakyThrows
    @ResponseBody
    @GetMapping("/code")
    public R<String> code(String tableIds) {
        //生成代码
        for (String tableId : tableIds.split(",")) {
            generatorService.generatorCode(Long.valueOf(tableId));
        }
        return R.success();
    }


    /**
     * 预览代码
     *
     * @param tableId 表ID
     * @return
     */
    @SneakyThrows
    @GetMapping("/preview")
    public List<Map<String, String>> preview(Long tableId) {
        return generatorService.preview(tableId);
    }
}
